package controller;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import session_beans.AirTransportSessionBean;
import session_beans.AirTransportSessionRemote;
import entity_beans.User;


/**
 * Servlet implementation class for Servlet: LoginServlet
 *
 */
public class LoginServlet extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {

	private static final long serialVersionUID = -8872684437263883285L;
	
	
	private AirTransportSessionRemote airTransportSession;

	
	@Override
	public void init() throws ServletException {
		super.init();
		
		airTransportSession = new AirTransportSessionBean();
	}

	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}
	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		String userParam = request.getParameter("user");
		String passParam = request.getParameter("pass");

		if (userParam == null || passParam == null) {
			response.sendRedirect("viewer/login.jsp");
			return;
		}
		
		HttpSession session = request.getSession();
		
		User user = (User) session.getAttribute("user");
		
		user.setUsername(userParam);
		user.setPassword(passParam);
		
		if ( user.isLoggedIn() == true ) {
			response.sendRedirect("viewer/main.jsp");
			return;
		}
		
		if ( airTransportSession.loginUser(user) == true ) {
			user.login();
			response.sendRedirect("viewer/main.jsp");
			return;
		}
		else {
			response.sendRedirect("viewer/login.jsp");
			return;
		}
		
	}

}
